/**
 * 通用uni-app网络请求
 * 基于 Promise 对象实现更简单的 request 使用方式，支持请求和响应拦截
 */

/*
// 开放的接口
import http from './interface'

http.config.baseUrl = "http://localhost:8080/api/"

http.request(url:'user/list',method:'GET').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list').then((res)=>{
	console.log(JSON.stringify(res))
})
http.get('user/list', {status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.post('user', {id:1, status: 1}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.put('user/1', {status: 2}).then((res)=>{
	console.log(JSON.stringify(res))
})
http.delete('user/1').then((res)=>{
	console.log(JSON.stringify(res))
}) 

*/
// import store from '@/store'
// import { msg as Toast } from '@/utils/util'
// import cache from '@/utils/cache'
// import { navToLoginUrl } from '@/util/http/auto-login'
import { BASEURL, PRO_BASEURL, DEV_BASEURL } from '@/constant/index.js';
import * as tologin from '@/utils/app_interaction_h5/tologin.js';

const baseUrl =
  process.env.NODE_ENV === 'development' ? DEV_BASEURL : PRO_BASEURL;

let encryption = null;
// 异步导入
const asyncLoad = () => {
  if (encryption) return false;
  try {
    require.ensure([], () => {
      import('encryption').then((res) => {
        encryption = res.encryption;
      });
    });
  } catch (e) {
    uni.showModal({
      title: '错误',
      content: `导入失败：${JSON.stringify(e)}`,
      showCancel: false,
      cancelText: '知道了',
    });
    return Promise.reject(new Error(e));
  }
};
asyncLoad();

export default {
  config: {
    baseUrl,
    header: {
      'Content-Type': 'application/json;charset=UTF-8',
      // 'Content-Type':'application/x-www-form-urlencoded',
      // 'Platform-Token': platformToken
    },
    data: {},
    method: 'GET',
    dataType: 'json' /* 如设为json，会对返回的数据做一次 JSON.parse */,
    responseType: 'text',
    cache: '', // 缓存接口数据
    success() {},
    fail: (err) => {
      uni.showToast({
        title: '网络请求失败',
        duration: 2000,
        icon: 'none',
      });
      console.log(err);
    },
    complete() {},
  },
  interceptor: {
    request: (config) => {
      return config; // 必须返回配置
    },
    response: (response) => {
      return response;
    },
  },
  request(options) {
    if (!options) {
      options = {};
    }
    options.baseUrl = options.baseUrl || this.config.baseUrl;
    options.dataType = options.dataType || this.config.dataType;
    options.url = options.baseUrl + options.url;
    options.data = options.data || {};
    options.method = options.method || this.config.method;

    return new Promise((resolve, reject) => {
      let _config = null;

      options.complete = (response) => {
        let statusCode = response.statusCode;
        response.config = _config;
        if (this.interceptor.response) {
          let newResponse = this.interceptor.response(response);
          if (newResponse) {
            response = newResponse;
          }
        }
        if (statusCode === 200) {
          //成功
          // 缓存数据
          let key =
            options.cache && options.cache.uni
              ? options.url + options.cache.uni
              : options.url;
          options.cache && cache.put(key, response, options.cache.cacheTime);

          // 未登录时，跳转登录页
          if (response.data.errCode == '401') {
            tologin.toAppLogin();
          }

          resolve(response);
        } else {
          reject(response);
        }
      };

      _config = Object.assign({}, this.config, options);
      _config.requestId = new Date().getTime();

      if (this.interceptor.request) {
        this.interceptor.request(_config);
      }

      // 缓存读取
      if (_config.cache) {
        let key = _config.cache.uni
          ? _config.url + _config.cache.uni
          : _config.url;
        let response = cache.get(key);
        if (response !== false) {
          resolve(response);
          return;
        }
      }

      // 是否需要验证登录
      if (_config.header.auth) {
        let token_type = 'bearer';
        let acc_token = '';
        let acc_token_header_key = 'Authorization';
        const token = uni.getStorageSync('wxlsToken');
        if(token) _config.header[acc_token_header_key] = `${token_type} ${token}`;
      }

      if (
        process.env.NODE_ENV === 'production' &&
        _config.header.encryption &&
        encryption
      ) {
        // 需要加密且存在加密包时
        _config.data = JSON.parse(encryption(JSON.stringify(_config.data)));
      }

      uni.request(_config);
    });
  },

  get(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = 'GET';
    return this.request(options);
  },
  post(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = 'POST';
    return this.request(options);
  },
  put(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = 'PUT';
    return this.request(options);
  },
  delete(url, data, options) {
    if (!options) {
      options = {};
    }
    options.url = url;
    options.data = data;
    options.method = 'DELETE';
    return this.request(options);
  },
};
